// 单例 模式
import { createButtonGroup } from './create-temp.js'
export function getSingleClass(fn) {
  let result
  return function (...params) {
    return result || (result = new fn(...params))
  }
}

export class BaseClass {
  static getSingleClass(fn) {
    let result
    return function (...params) {
      return result || (result = new fn(...params))
    }
  }
}
/*
export function untilValueExist(getValue, cb, expiration = 20 * 1000) {
  const startTime = Date.now()
  ;(function recursive() {
    requestAnimationFrame(() => {
      const value = getValue()
      if (value) {
        cb(value)
      } else {
        if (Date.now() - startTime < expiration) {
          recursive()
        } else {
          console.warn('优化吧')
        }
      }
    })
  })()
}
  */

export function waitUntilValueExist(getValue, expiration = 1000) {
  return new Promise((resolve, reject) => {
    const startTime = Date.now()
    ;(function recursive() {
      requestAnimationFrame(() => {
        const value = getValue()
        if (value) {
          resolve(value)
        } else {
          if (Date.now() - startTime < expiration) {
            recursive()
          } else {
            console.warn('优化吧')
            reject('超时了')
          }
        }
      })
    })()
  })
}
/* 去掉原型链上的属性，只保留对象本身的属性, 如直接
    const c1 = getObjectByOwnPropertyNames(new Cesium.Cartesian3(1, 2, 3))
    const c2 = getObjectByOwnPropertyNames(new Cesium.Cartesian3(10, 2, 3))
*/
export function getObjectByOwnPropertyNames(obj) {
  return Object.getOwnPropertyNames(obj).reduce((acc, key) => {
    acc[key] = obj[key]
    return acc
  }, {})
}

// 保存JSON数据为可下载文件
import { saveAs } from 'file-saver'
/**
 * Saves JSON data as a downloadable file
 * @param {Object} data - The JSON object to save
 * @param {string} filename - The name of the file (without extension)
 */
export function saveJsonFile(data, filename = new Date().toLocaleDateString()) {
  // Convert the JSON object to a string with formatting
  const jsonString = JSON.stringify(data, null, 2)

  // Create a Blob with the JSON data and specify the MIME type
  const blob = new Blob([jsonString], { type: 'application/json' })

  // Use FileSaver's saveAs function to save the file
  saveAs(blob, `${filename}.json`)
}
